package com.test.netty.handler;

import com.test.netty.entity.Invocation;
import com.test.netty.register.LocalRegister;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.lang.reflect.Method;

public class NettyServerHandler extends SimpleChannelInboundHandler<Object> {

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {

        System.out.println("NettyServerHandler.channelRead msg:" + msg.toString());

        Invocation invocation = (Invocation) msg;
        Class<?> serviceImpl = LocalRegister.get(invocation.getInterfaceName());

        Method method = serviceImpl.getMethod(invocation.getMethodName(), invocation.getParamType());

        Object result = method.invoke(serviceImpl.newInstance(), invocation.getParams());

        System.out.println("NettyServerHandler.result" + result.toString());
        ctx.writeAndFlush(result);
    }


    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        cause.printStackTrace();
        ctx.close();
    }
}
